--fazer mini app: https://developers.google.com/image-search/v1/jsondevguide?hl=pt-BR

--[[***************************
 * Copyright (c) 2013 Fundação CERTI.
 * All rights reserved.
 ***********************]]

-- Example of using for Images moving

require("config")
require(SB_REQUIRE_LUAGUI .. "Keyboard")
require(SB_REQUIRE_LUAGUI .. "widgets.TextEdit")
require(SB_REQUIRE_LUAGUI .. "widgets.PasswordField")

local http = require("socket.http")


require('volume')
require("media")
require("channels")
require('application')
require('basicZapper')
require('remoteControl')
require('zapping')


require('graphic-toolkit.toolkit.guilt')
require('IterateTimer')

local channelGlobo, channelBand, channelSbt, channelRecord
local iconVolumeMute, iconVolume0, iconVolume1, iconVolume2, iconVolume3, iconNoAction
local iconMediaNormal, iconInputNormal, iconPictureNormal, iconAudioNormal, iconSettingsNormal, iconAppNormal
local iconAppFocus, iconMediaFocus, iconInputFocus, iconPictureFocus, iconAudioFocus, iconSettingsFocus, bgMenuFocus
local json = nil
--local channels = nil
local imageIconsNormal = nil
local imageIconsFocus = nil
local iconVolume = nil
local volumeTv = nil
local channel = nil


local nameMenu = {"Aplicações", "Media Center", "Entrada", "Imagem", "Audio", "Configurações"}
local avaliableChannels = {"AV","3","7","9","13", "45", "19"}
local posChannel = 0
local posMenuPrincipal = 1
local volume = 1--control.getVolume ()
local showMenu = false
local clearVolume
local setChannel = ""
local cancelChangeChannel = nil
local canEnter = true
local keyboard = nil
local textEditU, textEditUP = nil
local red, green, blue, transparency = 150, 150, 150, 255
local canal = 0
local x, y,w, h = nil 
local lenghtChannel = 2
local ChannelList = nil
idChannel = 1
lastChannelId = nil
local isMute = false -- variavel temporaria de teste para controlar se a tv está muda ou não

local function loadImages()
	channelGlobo = canvas:new('res/globo.png')
	channelBand = canvas:new('res/band.png')
	channelSbt = canvas:new('res/sbt.png')
	channelRecord = canvas:new('res/record.png')
	channelRedeVida = canvas:new('res/redevida.png')
	channelSenado = canvas:new('res/senado.png')

	iconVolumeMute = canvas:new('res/icon/ico-mute.png')
	iconVolume0 = canvas:new('res/icon/ico-volume_00.png')
	iconVolume1 = canvas:new('res/icon/ico-volume_01.png')
	iconVolume2 = canvas:new('res/icon/ico-volume_02.png')
	iconVolume3 = canvas:new('res/icon/ico-volume_03.png')
	iconNoAction = canvas:new('res/icon/ico-no_action.png')

	iconAppNormal = canvas:new('res/icon/ico-apps.png')
	iconMediaNormal = canvas:new('res/icon/ico-media_center.png')
	iconInputNormal = canvas:new('res/icon/ico-input.png')
	iconPictureNormal = canvas:new('res/icon/ico-picture.png')
	iconAudioNormal = canvas:new('res/icon/ico-sound.png')
	iconSettingsNormal = canvas:new('res/icon/ico-settings.png')

	iconAppFocus = canvas:new('res/icon/ico-apps_focus.png')
	iconMediaFocus = canvas:new('res/icon/ico-media_center2.png')
	iconInputFocus = canvas:new('res/icon/ico-input_focus.png')
	iconPictureFocus = canvas:new('res/icon/ico-picture_focus.png')
	iconAudioFocus = canvas:new('res/icon/ico-sound_focus.png')
	iconSettingsFocus = canvas:new('res/icon/ico-settings_focus.png')

	bgMenuFocus = canvas:new('res/icon/selectMenu.png')
	channelss = {}
	
	channelss["AV"] =  channelGlobo 
	channelss["3"] =  channelGlobo 
	channelss["7"] = channelBand
	channelss["9"] =  channelSbt
	channelss["13"] =   channelRecord
	channelss["19"] =   channelRedeVida
	channelss["45"] =   channelSenado
	imageIconsNormal = {iconAppNormal, iconMediaNormal, iconInputNormal, iconPictureNormal, iconAudioNormal, iconSettingsNormal}
	imageIconsFocus = {iconAppFocus, iconMediaFocus, iconInputFocus, iconPictureFocus, iconAudioFocus, iconSettingsFocus}
	iconVolume = {iconVolume0 ,iconVolume1 , iconVolume2, iconVolume3}
end


function searchKeyboardHandler(evt)
	if(canEnter) then
		canEnter = false
	else
		keyboard:handler(evt)
	end
	if (evt.class == 'key' and evt.type == 'press') then
		if (evt.key == 'BACK' ) then
			keyboard:setRunning(false)
			keyWordSearch = textEditU:text():gsub(" ", "")
			event.unregister(searchKeyboardHandler)
			local requisicao = 'https://ajax.googleapis.com/ajax/services/search/images?v=1.0&q='..keyWordSearch
			requisicao = http.request(requisicao)
			requisicao= json:decode(requisicao)
			--~ print(json.decode(requisicao))
			
			for i,v in pairs(requisicao.responseData.results) do 
				print(i,v.url)
				file  = io.open("img/"..i..".jpg", "w+") 
				imagem  = http.request(v.url)
				
				file:write(imagem)
				
				file:close()
				imagem = canvas:new("img/"..i..".jpg")
				imagem:attrScale(200,100)
				canvas:compose(i * 200, 0, imagem)
				canvas:flush()
			end
			
			event.register(onKeyPress)
			canEnter = false
			textEditU._cursorVisible = false
			
			verticalNavigationSearch = 2
			
			canvas:flush()
		end
	end
end

local function showKeyboard(handlerFunction, isPassword,x, y, width, height, refresh, textDefault1 )
	local textDefault = nil
	if rEdit then 
		textDefault = rEdit:text()
	else
		textDefault = textDefault1 or  ""
	end
	local currentText = nil
	if(isPassword) then
		textEditUP = PasswordField:new():oneline(true)
		textEditUP._x= x 
		textEditUP._y= y
		textEditUP._width= width
		textEditUP._height= height
		textEditUP:text(textDefault)
		textEditUP._style = Style:new()
		:backgroundColor(Color:new(255, 255, 255, 255))
		:fontColor(Color:new(red, green, blue, transparency))
		:shadowColor(Color:new(0, 0, 0, 0))
		:frameColor(Color:new(0, 0, 0, 0))
		textEditUP:style():fontSize(17)
		textEditUP:visible(true)
		textEditUP._cursorVisible = false
		textEditUP:draw()
		currentText = textEditUP
	else
		textEditU = TextEdit:new():oneline(true)
		textEditU._x= x 
		textEditU._y= y
		textEditU._width= width
		textEditU._height= height
		textEditU:text(textDefault)
		
		textEditU._style = Style:new()
		:backgroundColor(Color:new(255, 255, 255, 255))
		:fontColor(Color:new(red, green, blue, transparency))
		:shadowColor(Color:new(0, 0, 0, 0))
		:frameColor(Color:new(0, 0, 0, 0))
		textEditU:style():fontSize(17)
		textEditU:visible(true)
		textEditU:cursor(#textDefault+1)
		textEditU._cursorVisible = false
		textEditU:draw()
		currentText = textEditU
	end
	print("----------------meio")
	if not(refresh) then
		keyboard = Keyboard:new(currentText, 938, 305, "v3")
		keyboard:setRunning(false)
		keyboard:draw()
	else
		canEnter = true
		currentText._cursorVisible = true
		currentText:text(textDefault)
		currentText:draw()
		keyboard:setTextEdit(currentText)
		keyboard:setRunning(true)
		event.unregister(onKeyPress)
		event.register(handlerFunction)
	end	
	
	print("----------------fim")
end



local function getColor()
	return 0,0,0,255
end

local function clearBackground(x,y, widht, height, canFlush)
	if avaliableChannels[posChannel + 1] == "AV" then
		getFlowTV()
	else
		canvas:compose(x,y,channelss[avaliableChannels[posChannel + 1]], x, y, widht, height)
	end
	if(canFlush)then
		canvas:flush()
	end

end

local function alignCenter(x_box, text, sizeFont)
	canvas:attrFont("Lato", sizeFont, "normal")
	local x = canvas:measureText(text)
	local aux = x_box - x
	return (aux/2)
end

local function drawBarVolume(fixVolume)
	fixVolume = fixVolume or false
	canvas:attrFont('Lato', 30)
	canvas:attrColor(229,229,229,255)

	if(clearVolume) then
		clearVolume()
	end
	clearBackground(1185,0, 120, 120, false)
	canvas:attrFont('Lato', 30)
	canvas:attrColor(229,229,229,255)
	if(volume == 0) then
		fixVolume = true
		canvas:compose(1195,20,iconVolumeMute)
		canvas:drawText(1185, 55,"MUTE")	
	else
		local image = math.ceil(volume / 25)
		canvas:compose(1195,20,iconVolume[image])
		canvas:drawText(1190, 55,tostring(volume))	
	end
	canvas:flush()

	if(not fixVolume)then
		print ("=================== vou limpar o volume")
		clearVolume = event.timer(2000, function()
			clearBackground(1185,0, 120, 120, true)
		end)
	end
end

local function paintImage(canDrawVolume)

	if (avaliableChannels[posChannel+1]== "AV") then 
		getFlowTV()
	else 
		canvas:compose(0,0,channelss[avaliableChannels[posChannel+1]])
	end
	if(volume == 0)then
		drawBarVolume(true)	
	else 
		canvas:flush()
	end
	
end





local function changeChannel(numberChannel)
	if #setChannel < lenghtChannel then
		setChannel = setChannel..numberChannel
	
	canvas:attrFont('Lato', 25)
	canvas:attrColor(229,229,229,255)

	if(cancelChangeChannel) then
		cancelChangeChannel()
	end
	clearBackground(1190,0, 100, 100, false)
	canvas:drawText(1200, 40, setChannel)	
	canvas:flush()
	print("canal",avaliableChannels[tostring(tonumber(setChannel))])
	
	
	cancelChangeChannel = event.timer(2000, function()
		print("esotu aqui")
		for i,v in pairs(avaliableChannels) do
		if(v == tostring(tonumber(setChannel)))then
			posChannel = tonumber(i)-1
			paintImage()
			break
		else
					
			print("vou mudar de canal")
			if not avaliableChannels[tostring(tonumber(setChannel))] then      -------caso houver erro de mudanca de canal
				canvas:compose(1198,38,iconNoAction)							--------
			end																	--------
			canvas:flush()				
			
			
			
			
			
			
			event.timer(1000, function()                        -------Aqui limpa os desenhos caso não mudar de canal
				lenghtChannel= 2								-------
				print("entrei no lugar estranho")				-------
				clearBackground(1190,0, 100, 100, true)			-------
			end)
			
		end
		end
		setChannel = ""			

	end)
	end
end






local function drawButtonMenu(pos, isSelect)
	if(isSelect)then
		canvas:attrColor(0,0,0, 255)
		canvas:drawRect ("fill", 0 + ((pos-1) * 214), 580, 214 , 140)
		canvas:compose(0 + ((pos-1) * 214),580,bgMenuFocus)	
		canvas:compose(72 + ((pos-1) * 214),610,imageIconsFocus[pos])	
		
		canvas:attrFont('Lato', 24)
		canvas:attrColor(255,255,255,255)
		canvas:drawText(alignCenter(214, nameMenu[pos], 24) + ((pos-1) * 214), 680,nameMenu[pos])
		
	else
		canvas:attrColor(0,0,0, 255)
		canvas:drawRect ("fill", 0 + ((pos-1) * 214), 580, 214 , 140)
		canvas:compose(72 + ((pos-1) * 214),610,imageIconsNormal[pos])
		
		canvas:attrFont('Lato', 20)
		canvas:attrColor(229,229,229,255)
		canvas:drawText(alignCenter(214, nameMenu[pos], 20) + ((pos-1) * 214), 680,nameMenu[pos])	
	end
	
	
end
local function drawMenu()
	canvas:attrColor(0,0,0, 255)
	canvas:drawRect ("fill", 0, 580, 1280 , 140)
	
	for i=1, #imageIconsNormal do
		if(i == posMenuPrincipal)then
			drawButtonMenu(i, true)
		else
			drawButtonMenu(i, false)
		end
	end
		
	canvas:flush()
end



--------------------------------------------------
-- HANDLERS
--------------------------------------------------
-- esse é o handler velho

function onKeyPress(evt)
for i,v in pairs (evt) do
print (i,v)
end
	if evt.class == 'key' and evt.type == 'press' then
		print("====================+", evt.class, evt.type, type(evt.key))
		if(evt.key == 'MENU') then
			if(not showMenu)then
				drawMenu()
			else
				clearBackground(0, 580, 1280 , 140, true)
			end
			showMenu = not showMenu
		elseif(evt.key == 'EXIT') then
				--control.powerOff() -- desligar a tv
				application.notifyDestroy()				
		elseif (evt.key == '100') then 
		lenghtChannel = 3
		changeChannel('1')
		elseif (evt.key == 'MUTE') then 
			print(isMute)
			if(isMute) then
				control.unmuteAudio(control.getCurrentAudio())
				unmuteAudio()
				isMute = false
			else
				print("entoru na condicao")
				control.muteAudio(control.getCurrentAudio())				
				tVolumeGui.open("MUTE")
				isMute = true
			end				
		
		elseif(evt.key == 'ENTER') then
			if(showMenu and posMenuPrincipal == 1) then
				showKeyboard(searchKeyboardHandler, false,940, 255, 280, 30, false)
				showKeyboard(searchKeyboardHandler, false,940, 255, 280, 30, true)
			end
			
		elseif(evt.key == 'VOLUME_DOWN') then
			if(isMute) then
				control.unmuteAudio(control.getCurrentAudio())
				unmuteAudio()
				isMute = false
			end	
			control.volumeDown(control.getCurrentAudio()) -- diminuir o volume					
			tVolumeGui.open(evt.key)
			
		elseif (evt.key == 'VOLUME_UP') then
			if(isMute) then
				control.unmuteAudio(control.getCurrentAudio())
				unmuteAudio()
				isMute = false
			end			
			control.volumeUp(control.getCurrentAudio()) -- aumentar o volume						
			tVolumeGui.open(evt.key)			
			
		elseif(evt.key == 'VOLUME_UP_REP') then
			volumeUpRep()
			
			
			--~ control.setVolume(control.getVolume(control.getCurrentAudio()) + 2) -- aumentar o volume						
			--~ tVolumeGui.open(evt.key)	
		
			
		elseif(evt.key == 'VOLUME_DOWN_REP') then
			volumeDownRep()
				
		elseif(evt.key == 'CHANNEL_DOWN') then	
			if(isMute) then
				control.muteAudio(control.getCurrentAudio())
				muteAudio()				
			end	
		
			lastChannelId = control.getCurrentChannel().id	 -- salvar o ultimo canal
			changeChannelByDirection("DOWN")
			tZappingGui.open(evt.key)					
			event.timer(1000,function() getFlowTV() end)
				
		elseif (evt.key == 'CHANNEL_UP') then
			if(isMute) then
				control.muteAudio(control.getCurrentAudio())
				muteAudio()				
			end	
			lastChannelId = control.getCurrentChannel().id    -- salvar o ultimo canal
			
			changeChannelByDirection("UP")
			tZappingGui.open(evt.key)									
			event.timer(1000,function() getFlowTV() end)
		elseif(evt.key == 'CURSOR_UP') then			
			getFlowTV()
			canvas:flush()
			
		elseif (evt.key == 'CURSOR_LEFT') then
			if(showMenu)then
				if(posMenuPrincipal > 1)then
					drawButtonMenu(posMenuPrincipal, false)
					posMenuPrincipal = posMenuPrincipal - 1
					drawButtonMenu(posMenuPrincipal, true)
					canvas:flush()
				end
			end
			
		elseif (evt.key == 'YELLOW') then	
			drawChannel() --desenhar os tributos de canal
			drawChannel2()
			
		elseif (evt.key == 'RED') then	
			eraseTest() -- apagar os testes
			
		elseif (evt.key == 'BLUE') then
			changeVolumeTest() -- funcao para desenhar os atributos de som, só para teste	
			
		elseif (evt.key == 'BACK') then -- botao para voltar pro ultimo canal em que ele estava			
			if(lastChannelId) then	
				local currentChannel = control.getCurrentChannel().id				
				control.selectChannel(lastChannelId)
				idChannel = 	lastChannelId
				lastChannelId = currentChannel
				drawChannelNumber(tostring(tonumber(control.getCurrentChannel().physNumber)))
			end				
		elseif (evt.key == 'CURSOR_UP') then
			print(holdingVolDown)
			holdingVolDown = true
			
		elseif (evt.key == 'CURSOR_RIGHT') then
			if(showMenu)then				
				if(posMenuPrincipal < #imageIconsNormal)then
					drawButtonMenu(posMenuPrincipal, false)
					posMenuPrincipal = posMenuPrincipal + 1
					drawButtonMenu(posMenuPrincipal, true)
					canvas:flush()
				end
			end
		elseif (tonumber(evt.key)) then			
			changeChannelByNumberZapping(evt.key)
		end		
	else
		--print('NO ACTION FOR PRESSED KEY "' .. evt.key .. '" , "'.. evt.type..'"')
	end
end



function volumeDownRep()
	event.timer(400, function() 
		--control.setVolume(control.getVolume(control.getCurrentAudio()) - 2) -- diminuir  o volume			
		control.volumeDown(control.getCurrentAudio())
		control.volumeDown(control.getCurrentAudio())			
		tVolumeGui.open('VOLUME_DOWN_REP')
		if(holdingVolDown) then	
			volumeDownRep()
		else 
			return
		end	
	end)		
end			

function volumeUpRep()	
	event.timer(400, function() 
		control.setVolume(control.getVolume(control.getCurrentAudio()) + 2) -- aumentar o volume	
		control.volumeUp(control.getCurrentAudio())
		control.volumeUp(control.getCurrentAudio())					
		tVolumeGui.open('VOLUME_UP_REP')
		if(holdingVolUp) then	
			volumeUpRep()
		else 
			return
		end	
	end)		
end				
	
function eraseTest()
	print("entrando no erase")
	canvas:attrColor(0,0,0,255)
	canvas:drawRect("fill",0,0,250,700)
	canvas:drawRect("fill",1200,40,45,40)
	
	canvas:flush()
end	


-------------funcao para desenhar o numero do canal -------------------
function drawChannelNumber(channelNumber)
	print("entrou no drawChannelNumber")	
	createNumber(channelNumber)
	print("conseguiu acabar o createNumber")
	event.timer(1000,function() hide() dispose() end)
end


----------------funcao para mudar o volume--------------
function changeVolumeTest()	
	DrawTest(control.getCurrentAudio().type,0)
	DrawTest(control.getCurrentAudio().description,30)
	DrawTest("teste escrita",60)
	DrawTest(control.getVolume(control.getCurrentAudio()),90)
end	





---------------funcao para desenhar testes -------
function DrawTest(testeVolume,largura,altura)		
	canvas:attrFont("Lato", 24, "normal")
	canvas:attrColor(170,170,170,255)
	
	retorno = testeVolume	
	
	if(retorno == nil) then
		retorno = "Nada"
	end
	if(retorno == true) then
		retorno = "true"
	end
	if(retorno == false) then
		retorno = "false"
	end	
	print(retorno)
	canvas:drawText(largura,altura,retorno)	
	
	canvas:flush()
end


--~ 
--~ function onKeyPress(evt)
--~ print("entrando no onKeyPress")
--~ 
--~ 
	--~ print("o evento é :" )
	--~ print(evt)
		--~ if(evt == 'MENU') then
			--~ if(not showMenu)then
				--~ drawMenu()
				--~ return true
			--~ else
				--~ clearBackground(0, 580, 1280 , 140, true)
				--~ return true
			--~ end
			--~ showMenu = not showMenu
			--~ return true
		--~ elseif(evt == 'EXIT') then
				--~ control.powerOff()
				--~ --application.notifyDestroy()
		--~ elseif (evt == '100') then 
		--~ lenghtChannel = 3
		--~ changeChannel('1')
		--~ return true
		--~ elseif (evt == 'MUTE') then 
		--~ volume = 0
		--~ drawBarVolume(true)
		--~ 
		--~ elseif(evt == 'ENTER') then
			--~ DrawTest()
			--~ if(showMenu and posMenuPrincipal == 1) then
				--~ showKeyboard(searchKeyboardHandler, false,940, 255, 280, 30, false)
				--~ showKeyboard(searchKeyboardHandler, false,940, 255, 280, 30, true)
				--~ return true
			--~ end
			--~ return true
		--~ elseif(evt == 'VOLUME_DOWN') then
			--~ if(volume > 0)then
				--~ volume = volume - 1
			--~ end
			--~ drawBarVolume()
			--~ return true
		--~ elseif (evt == 'VOLUME_UP') then
			--~ if(volume < 100)then
				--~ volume = volume + 1
			--~ end
			--~ drawBarVolume()
			--~ return true
			--~ 
		--~ elseif(evt == 'CHANNEL_DOWN') then
			--~ showMenu = false
			--~ posChannel = (posChannel - 1) % #avaliableChannels
			--~ paintImage()
			--~ return true
			--~ 
		--~ elseif (evt == 'CHANNEL_UP') then
			--~ print("aprasentarei o nome do canal")
			--~ tabelaCanal = control.getCurrentChannel()
			--~ --print(tabelaCanal[1])
			--~ print(control.getCurrentChannel())
			--~ showMenu = false
			--~ posChannel = (posChannel + 1) % #avaliableChannels
			--~ paintImage()
			--~ return true
			--~ 
		--~ elseif (evt == 'CURSOR_LEFT') then
			--~ if(showMenu)then
				--~ if(posMenuPrincipal > 1)then
					--~ drawButtonMenu(posMenuPrincipal, false)
					--~ posMenuPrincipal = posMenuPrincipal - 1
					--~ drawButtonMenu(posMenuPrincipal, true)
					--~ canvas:flush()
					--~ return true
				--~ end
			--~ end
			--~ return true
			--~ 
		--~ elseif (evt== 'CURSOR_RIGHT') then
			--~ if(showMenu)then				
				--~ if(posMenuPrincipal < #imageIconsNormal)then
					--~ drawButtonMenu(posMenuPrincipal, false)
					--~ posMenuPrincipal = posMenuPrincipal + 1
					--~ drawButtonMenu(posMenuPrincipal, true)
					--~ canvas:flush()
					--~ return true
				--~ end
			--~ end
			--~ return true
		--~ elseif (tonumber(evt.key)) then
			--~ 
			--~ changeChannel(evt.key)
		--~ end
		--~ 
		--~ 
		--~ 
	--~ 
--~ end




-------------- funcao de teste para desenhar os atributos da tv -----------------------
function drawChannel()
	local channelTest = control.getCurrentChannel()
	
	
	--id
	DrawTest("id",100,0)
	DrawTest(control.getCurrentChannel().id,0,0)
	--number
	DrawTest("number",100,30)
	DrawTest(control.getCurrentChannel().number,0,30)
	--PhysNumber
	DrawTest("PhysNumber",100,60)
	DrawTest(control.getCurrentChannel().physNumber,0,60)
	--source
	DrawTest("Source",100,90)		
	DrawTest(control.getCurrentChannel().source,0,90)
	--sourceType
	DrawTest("SourceType",100,120)		
	DrawTest(control.getCurrentChannel().sourceType,0,120)	
	--service
	DrawTest("Service",100,150)		
	DrawTest(control.getCurrentChannel().service,0,150)	
	--type
	DrawTest("type",100,180)		
	DrawTest(control.getCurrentChannel().type,0,180)	
	--name
	DrawTest("name",100,210)		
	DrawTest(control.getCurrentChannel().name,0,210)
	--blocked
	DrawTest("blocked",100,240)		
	DrawTest(control.getCurrentChannel().blocked,0,240)
	
	
	
end

function drawChannel2()

--skipped
	print("pasosu pelo skipped")
	DrawTest("skipped",100,270)		
	DrawTest(control.getCurrentChannel().skipped,0,270)
	--favorite
	DrawTest("favorite",100,300)		
	DrawTest(control.getCurrentChannel().favorite,0,300)
	--primary
	DrawTest("primary",100,330)		
	DrawTest(control.getCurrentChannel().isPrimary,0,330)
	--oneseg
	DrawTest("oneseg",100,360)		
	DrawTest(control.getCurrentChannel().oneseg,0,360)
	--frequency
	DrawTest("frequency",100,390)		
	DrawTest(control.getCurrentChannel().frequency,0,390)
	--isDigital
	DrawTest("isdigital",100,420)		
	DrawTest(control.getCurrentChannel().isDigital,0,420)
end	


----------- funcao para mudar de canal para cima e para baixo --------------
function changeChannelByDirection(direction)
	if(#ChannelList < 2) then
		return
	end	
	
	if direction == "UP" then		
	
		idChannel = idChannel + 1
		
		if(idChannel > #ChannelList) then
			idChannel = 1
		end
		
					
		control.selectChannel(idChannel)
	end	
	
	if direction == "DOWN" then
		idChannel = idChannel -1
	
		if(idChannel == 0) then
			idChannel = #ChannelList
		end	
		
		control.selectChannel(idChannel)
	end	
end

----------- funcao para mudar de canal pelo numero--------------
function changeChannelByNumber(number)		
	number = tonumber(number) -- transformar a string em numero
	
	if(#ChannelList < 1) then
		return
	end
	
	for i,v in ipairs(ChannelList) do		
		if(number == v.physNumber) then		
			idChannel = v.id -- quando mudar o canal, atualizar a varivavel que controla a direção para cima e para baixo
			control.selectChannel(v.id)
		end
	end
	
	return
end			


 function changeChannelByNumberTest(numberChannel)
	--~ if(#ChannelList < 1) then
		--~ return
	--~ end
	
	if #setChannel < lenghtChannel then
		setChannel = setChannel..numberChannel
		
		canvas:attrFont('Lato', 35)
		canvas:attrColor(229,229,229,255)
		
		
		
		if(cancelChangeChannel) then
			cancelChangeChannel()
		end
		clearBackground(1190,0, 100, 100, false)
		canvas:drawText(1200, 40, setChannel)	
		canvas:flush()
		print("entrei aqui depois do flush")
		
		
		cancelChangeChannel = event.timer(2000, function()
		
			--~ for i,v in pairs(avaliableChannels) do
			--~ if(v == tostring(tonumber(setChannel)))then
				--~ posChannel = tonumber(i)-1
				--~ paintImage()
				--~ break
			--~ else
						
			for i,v in ipairs(ChannelList) do				
				if(tostring(tonumber(setChannel)) == tostring(v.physNumber)) then	
					print("conseguir casar os canais")
					idChannel = v.id -- quando mudar o canal, atualizar a varivavel que controla a direção para cima e para baixo
					control.selectChannel(v.id)	
					setChannel = ""			
					return
				end				
			end
				
				canvas:compose(1198,38,iconNoAction)
				
				canvas:flush()
				
				event.timer(1000, function()
					lenghtChannel= 2
					clearBackground(1190,0, 100, 100, true)
				end)			
			
			setChannel = ""			

		end)
	end
end









--~ local function createTest()
	--~ 
   --~ -- Window to show OSD
   --~ print("entrei no createTest")
   --~ windowNumber = Window:new({width = 1280, height = 262})
   --~ print("entrei no createTest")
   --~ local boxNumber = Box:new()
   --~ boxNumber:setAnchors({fill = windowNumber})
--~ 
   --~ local imageShadow = Image:new({z = 1, fileName = 'resources/images/channel-number-bg.png'})
   --~ imageShadow:setAnchors({left = boxNumber.left, top = boxNumber.top})
--~ 
   --~ labelNumber = Label:new({z = 2, width = 1000, height = 105})
   --~ labelNumber:setActivated({size = 100, color = {241, 241, 241, 255}})
   --~ labelNumber:setShadow()
   --~ labelNumber:setAnchors({left = boxNumber.left, 
                           --~ top = boxNumber.top, 
                           --~ leftMargin = 34, 
                           --~ topMargin = 18})
   --~ 
   --~ labelNumber:setText('isso é apenas um teste')
  --~ 
   --~ boxNumber:add({imageShadow, labelNumber})
   --~ windowNumber:compose(boxNumber)
   --~ imageShadow = nil
   --~ boxNumber = nil
--~ end

















 function getFlowTV() -- para deixar a tela do aplicativo com o fluxo da tv
	require("media")	
	video = mediaPlayer:new('dtv://video')
	video:prepare()
	x, y,w, h = video:getBounds()
	video:setBounds(0, 0, 1280, 720)
	video:start()	
end


local function initializeVariables()	
	handlers.onStart()
	handlers.onCreate()
	
	
	--handlers.onKeyPress = onKeyPress
	
	ChannelList = channels.getChannelList()
	print(#ChannelList)
	
	
	json = require("util.json")
	event.register(onKeyPress)
	loadImages()
	getFlowTV()
	--createTest()
	
end




function indexPage()
	return true
end

initializeVariables()
